package com.smm.web.vmc.controller.User;

import com.google.code.kaptcha.Constants;
import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.dto.UserDto;
import com.smm.web.vmc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhenghao on 2016/8/31.
 *
 */
@Slf4j
@Controller
public class RegistController {

    @Resource
    private UserService userService;

    @Resource
    private VdioController vdioController;

    @RequestMapping("/regist.do")
    public ModelAndView regist(){

        return new ModelAndView("regist");
    }

    @RequestMapping("/submitRegist.do")
    public ModelAndView submitRegist(UserDto userDto,HttpServletRequest request){

        ModelAndView mv;

        try{

            //检查验证码
            if(StringUtils.isBlank(userDto.getCode()) || !checkCode(userDto.getCode(),request)){

                throw new Exception("验证码错误");
            }

            //保存用户信息
            User user = userService.regist(userDto);

            request.getSession().setAttribute(UserService.USER_SESSION_KEY,user);

            //跳转到视频列表页面
            mv = vdioController.list(request);

        }catch (Exception e){

            e.printStackTrace();

            log.error(String.valueOf(e));
            mv = new ModelAndView("regist");
            mv.addObject("err_msg",e.getMessage());

        }

        return mv;
    }


    //检查注册验证码。 成功返回true ，失败返回 false
    private boolean checkCode(String code, HttpServletRequest request) {

        String sessionCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        return sessionCode.equals(code.trim());
    }
}
